package com.nkzy.controller;

import cn.hutool.core.bean.BeanUtil;
import com.nkzy.domain.dto.UserfromDTO;
import com.nkzy.domain.pojo.Result;
import com.nkzy.domain.pojo.User;
import com.nkzy.domain.vo.UserVO;
import com.nkzy.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/user") //Restful 风格要求请求路径用表名+s
@RestController
public class UserController {
//Controller是前后端进行数据交互的桥梁，对于开发人员来说：我们要给前端开发人员提供接口的说明文档
@Autowired
    private UserService userService;
//保存数据
    @PostMapping
    @Operation(summary = "保存用户信息")
    public Result saveUSer(@RequestBody UserfromDTO userfromDTO){
//1.把DTO对象转换为POJO对象
       User  user = BeanUtil.copyProperties(userfromDTO,User.class);
//2.调用业务侧的保存的方法，完成增加用户信息
       userService.save(user);
       return Result.success();
    }
    //查询一个用户
    @GetMapping("/{id}")//RestFul格式的传参
    @Operation(summary = "查询一个用户")
    public Result getUser(@PathVariable Long id){
        //1.调用业务侧查询一个用户
        User user = userService.getById(id);
        //2.把pojo对象转换为vo对象
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //3.返回vo对象
        return Result.success(userVO);
    }
    //删除一个用户
@DeleteMapping("/{id}")
    @Operation(summary = "删除一个用户")
    public Result deleteUser(@PathVariable Long id){
        //1.调用业务侧删除一个用户
        userService.removeById(id);
        return Result.success();
    }
    //根据id的集合查询多个用户
    @GetMapping("/list")
    @Operation(summary = "根据id的集合查询多个用户")
    public Result getUsers(@RequestParam("ids") List<Long> ids){
        //1.调用业务侧查询多个用户
        List<User> users = userService.listByIds(ids);
        //2.把pojo对象转换为vo对象
         BeanUtil.copyToList(users, UserVO.class);
         return Result.success(users);
    }
    //查询所有用户
    @GetMapping("/all")
    @Operation(summary = "查询所有用户")
    public Result getAllUsers(){
        //1.调用业务层查询所有用户
        List<User> users = userService.list();
        //2.POJO对象转换为VO对象
        List<UserVO> usersVO = BeanUtil.copyToList(users, UserVO.class);
        return Result.success(usersVO);
    }
    //修改一个用户
    @PutMapping
    @Operation(summary = "修改一个用户")
    public Result updateUser(@RequestBody UserfromDTO userfromDTO){
        //1.把DTO对象转换为POJO对象
        User user = BeanUtil.copyProperties(userfromDTO, User.class);
        //2.调用业务侧修改一个用户
        userService.updateById(user);
        return Result.success();
    }
}
